'use strict';

/** *
 * @description 公共校验规则
 * */

// 校验手机号码
const validatorPhone = () => {
  return (rule, value, callback) => {
    const tel = /^0\d{2,3}-?\d{7,8}$/;
    const phone = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    value = value.toString();
    if (!value) {
      callback();
      return;
    }
    if (value.length === 11) { // 手机号码
      if (phone.test(value)) {
        callback();
        return;
      }
    } else if (value.length === 13 && value.indexOf('-') !== -1) {
      if (tel.test(value)) {
        callback();
        return;
      }
    }
    callback(new Error('请输入正确格式的号码'));
  };
};

// 校验非中文字符
const validatorNoZhCn = msg => {
  return (rule, value, callback) => {
    const pattern = /^[^\u4e00-\u9fa5]+$/;
    if (pattern.test(value)) {
      callback();
      return;
    }
    callback({ message: msg + '不得含有中文' });
  };
};

// 检验日期格式
const validatorDate = () => {
  return (rule, value, callback) => {
    const reg = /^(\d{4})-(\d{2})-(\d{2})$/;
    if (reg.test(value)) {
      callback();
      return;
    }
    callback({ message: '日期格式错误' });
  };
};

// 检验身份证号
const validatorNo = () => {
  return (rule, value, callback) => {
    const reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    if (reg.test(value)) {
      callback();
      return;
    }
    callback({ message: '身份证号错误' });
  };
};

const regArr = [ '敏感词' ];

// 校验敏感词汇
const validatorSensitive = () => {
  return (rule, value, callback) => {
    const reg = new RegExp(regArr.join('|'), 'i');
    if (!reg.test(value)) {
      callback();
      return;
    }
    callback({ message: '含有敏感词汇' });
  };
};

module.exports = {
  validatorPhone,
  validatorNoZhCn,
  validatorDate,
  validatorNo,
  validatorSensitive,
};
